/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, { Component } from 'react';
import {StyleSheet, Text, View, TouchableOpacity, CameraRoll, Platform, Dimensions, Animated, Easing, Image, NativeModules, Modal, Clipboard, PermissionsAndroid} from 'react-native';

import Toast from 'react-native-root-toast';
import Common from './common';

var totalWidth = Dimensions.get('window').width;

const JsAndroid = NativeModules.JsAndroid;

export default class Share extends Component {
  constructor(props) {
    super(props);
    this.state = {
      rotation: new Animated.Value(0),
      modalVisible: false,
      path: '',
      isTakeImg: false,
      flag: false,
      wechat: true,
      qq: true,
      weibo: true,
    };

  }
  componentWillMount(){
    if(Platform.OS == 'ios'){
      JsAndroid.checkThirdStatus((e) => {
        this.setState({
          wechat: e.wechat,
          qq: e.qq,
          weibo: e.weibo,
        })
      });
    }
  }
  componentDidMount(){
    this.startAnimate();
  }
  componentWillUnmount(){
    clearTimeout(this.timer);
  }
  startAnimate(){
    this.state.rotation.setValue(0);
    Animated.timing(this.state.rotation, {
      toValue: 1,
      duration: 1000,
      easing: Easing.linear
    }).start(()=>{this.startAnimate()}); 
  }
  show = (location,name,flag) => {
    this.setState({
      location: location,
      path: name,
      modalVisible: true,
      isShare: true,
      flag: flag,
      });
    // this.timer = setTimeout(()=> {
    //   Common.takeToImage(location, name, (uri) => {
    //     this.setState({path: name+".png"});
    //   },flag);
    //   clearTimeout(this.timer);
    // }, 400)
    
  };
  async share(type){
    let granted = true;
    if(Platform.OS == "android"){
      granted = await PermissionsAndroid.check(PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE);
    }
    if(granted){
      this.setState({isTakeImg: true});

      this.timer = setTimeout(() => {
        Common.takeToImage(this.state.location, this.state.path, (uri) => {
          // this.setState({path: name+".png"});
          // return uri
          
          JsAndroid.jsOpenShareActivity(uri, type, (e) => {
            if(e){
              console.log("success");
              this.iknow();
            }else{
              console.log("error");
              this.iknow();
            }
          },(e) => {
            console.log(e);
            this.iknow();
          })
        },this.state.flag);
        clearTimeout(this.timer)
      }, 2000);
    }else{
      // Toast.show("请到设置->应用->权限中打开SD卡读写权限！", {
      //   duration: Toast.durations.LONG,
      //   position: Toast.positions.CENTER,
      //   shadow: true,
      //   animation: true,
      //   hideOnPress: true,
      //   delay: 0});
      Common.userTip("请到权限管理中打开SD卡读写权限");
      this.iknow();
    }
  };
  onlyImage = () => {
    this.setState({isTakeImg: true});
    this.timer = setTimeout(() => {
      Common.takeToImage(this.state.location, this.state.path, (uri,root) => {
        this.iknow();
        if(root){
          uri = root + "/" +uri;
        }
        if(Platform.OS == "ios"){
          //先检查相册访问权限，之后保存图片 ios
          JsAndroid.checkAlbAuth((e) => {
            if(e){
              CameraRoll.saveToCameraRoll(uri,'photo');
              Toast.show("图片已保存到相册", {
                duration: Toast.durations.LONG,
                position: Toast.positions.BOTTOM,
                shadow: true,
                animation: true,
                hideOnPress: true,
                delay: 0});
            }else{
              Toast.show("请您先允许app访问相册", {
                duration: Toast.durations.LONG,
                position: Toast.positions.BOTTOM,
                shadow: true,
                animation: true,
                hideOnPress: true,
                delay: 0});
            }
          });
        }else{
            CameraRoll.saveToCameraRoll(uri,'photo');
            Toast.show("图片已保存到相册", {
              duration: Toast.durations.LONG,
              position: Toast.positions.BOTTOM,
              shadow: true,
              animation: true,
              hideOnPress: true,
              delay: 0});
        }
      },this.state.flag);
      clearTimeout(this.timer);
    }, 2000);
  };
  copyLink = () => {
    Clipboard.setString(this.state.path);
    this.iknow();
    Toast.show("已复制链接到剪贴板", {
        duration: Toast.durations.LONG,
        position: Toast.positions.CENTER,
        shadow: true,
        animation: true,
        hideOnPress: true,
        delay: 0});
  };
  iknow = () => {
    this.setState({modalVisible: false,isTakeImg: false});
  }
  render() {
    return (
      <Modal 
        animationType={"slide"}
        transparent={true}
        visible={this.state.modalVisible}
        onRequestClose={() => {if(!this.state.isTakeImg){this.iknow()}}}
       >
        <TouchableOpacity style={styles.mask} disabled={this.state.isTakeImg? true:false} onPress={this.iknow}>
          {
            this.state.isTakeImg?
            <View style={{backgroundColor: '#fff',padding: totalWidth*0.025, borderRadius: totalWidth*0.012, flexDirection: 'row'}}>
              <Animated.Image
                  source={require('../images/loading_small.png')}
                  style={{
                  transform: [{
                      rotateZ: this.state.rotation.interpolate({
                      inputRange: [0,1],
                      outputRange: ['0deg', '360deg']
                    })
                  }]
              }}/>
              <Text style={{marginLeft: totalWidth*0.05}}>正在生成长图片，请稍后……</Text>
            </View>
            :
          
          <TouchableOpacity style={styles.shareBox} activeOpacity={1}>
            <View style={styles.share}>
              {
                this.state.wechat?
                <TouchableOpacity style={styles.shareItem} onPress={() => this.share("circle")}>
                  <Image source={require('../images/share/MOMENT.png')} />
                  <Text style={styles.shareItemT}>微信朋友圈</Text>
                </TouchableOpacity>:null
              }
              {
                this.state.wechat?
                  <TouchableOpacity style={styles.shareItem} onPress={() => {this.share("weixin")}}>
                    <Image source={require('../images/share/WECHAT.png')} />
                    <Text style={styles.shareItemT}>微信好友</Text>
                  </TouchableOpacity>:null
              }
              {
                this.state.qq?
                  <TouchableOpacity style={styles.shareItem} onPress={() => {this.share("qq")}}>
                    <Image source={require('../images/share/QQ.png')} />
                    <Text style={styles.shareItemT}>QQ好友</Text>
                  </TouchableOpacity>:null
              }
              {
                this.state.qq?
                  <TouchableOpacity style={styles.shareItem} onPress={() => {this.share("qzone")}}>
                    <Image source={require('../images/share/QZONE.png')} />
                    <Text style={styles.shareItemT}>QQ空间</Text>
                  </TouchableOpacity>:null
              }
              {
                this.state.weibo?
                <TouchableOpacity style={styles.shareItem} onPress={() => {this.share("weibo")}}>
                  <Image source={require('../images/share/WEIBO.png')} />
                  <Text style={styles.shareItemT}>新浪微博</Text>
                </TouchableOpacity>:null
              }
              <TouchableOpacity style={styles.shareItem} onPress={this.onlyImage}>
                <Image source={require('../images/share/download.png')} />
                <Text style={styles.shareItemT}>保存图片</Text>
              </TouchableOpacity>
              {/*
              <TouchableOpacity style={styles.shareItem} onPress={this.copyLink}>
                <Image source={require('../images/share/LINK.png')} />
                <Text style={styles.shareItemT}>复制链接</Text>
              </TouchableOpacity>*/}
              {
                Platform.OS == "android"?
                <TouchableOpacity style={styles.shareItem} onPress={() =>{this.share("more")}}>
                  <Image source={require('../images/share/MORE.png')} />
                  <Text style={styles.shareItemT}>更多</Text>
                </TouchableOpacity>:null
              }
            </View>
            <TouchableOpacity style={styles.cancel} onPress={()=>this.iknow()}>
              <Text style={styles.cancelT}>取消</Text>
            </TouchableOpacity>
          </TouchableOpacity>
          }
        </TouchableOpacity>
      </Modal>
    )
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#f6f6f6',
  },
  page: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
  },
  toolbar: {
    backgroundColor: '#ff4546',
    zIndex: 2,
  },
  toolbarV: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'flex-start',
  },
  toolbarT: {
    color: '#ffffff',
    fontWeight: 'bold',
    fontSize: 20
  },
  mask: {
    flex: 1,
    backgroundColor:'rgba(0, 0, 0, 0.5)', 
    justifyContent: 'center',
    alignItems: 'center',
  },
  shareBox: {
    position: 'absolute',
    left: 0,
    bottom: 0,
    borderRadius: 0,
    backgroundColor: '#fff',
    
  },
  share: {
    width: totalWidth,
    flexDirection: 'row',
    flexWrap: 'wrap',
    marginHorizontal: totalWidth*0.037,
    marginTop: totalWidth*0.066,
    borderBottomWidth: 1,
    borderBottomColor: '#d6d6d6',
  },
  shareItem: {
    marginVertical: totalWidth*0.035,
    marginHorizontal: totalWidth*0.01,
    height: totalWidth*0.21,
    width: totalWidth*0.21,
    justifyContent: 'center',
    alignItems: 'center'
  },
  shareItemT: {
    marginTop: 5,
    color: '#242424',
    fontSize: 10
  },
  cancel: {
    height: totalWidth*0.2,
    alignItems: 'center',
    justifyContent: 'center',
    marginBottom: 0,
  },
  cancelT: {
    fontSize: 20,
    color: '#5b6878'
  }
});